<script lang="ts" setup>
  import { ref, onActivated, onDeactivated, watch } from 'vue';
  import { useToggle } from '@vueuse/shared';
  import { getCurrencyList, getQueryTokens, getQueryCarbonTrading } from '/@/apis/userApi';
  import { useRequest } from 'vue-request';
  const imgsmap = JSON.parse(localStorage.getItem('tokensImgsMap') as string);
  const isFrist = ref(true);
  // 弹出框显示
  defineProps<{
    list?: string[];
    title?: string;
    disabled?: boolean;
  }>();
  const type = ref('Cryptocurrencies');
  watch(
    () => type.value,
    () => {
      methodCurrencyList();
    },
    {
      immediate: true,
    },
  );
  // 定义外部事件
  const emit = defineEmits(['change']);
  const currencyList = ref<any[]>([]);
  // 内部事件
  const onClickItem = (itme: any, isInit?: boolean | string, isXz?: boolean) => {
    if (isXz) {
      return;
    }

    emit('change', itme, isInit);

    if (isInit === '1') {
      onToggleShow(false);
    }
  };
  const timer = ref();
  // 获取期货外汇列表
  function methodCurrencyList() {
    let tradeData = localStorage.getItem('trade') as string;
    // localStorage.setItem('trade', '');
    let jsondata: {
      nickName?: string;
      type?: string;
      pairsName?: string;
      name?: string;
      showPairsName?: string;
      symbol?: string;
    } = JSON.parse(tradeData || '{}');

    if (jsondata.type) {
      if (jsondata.type == 'CONTRACT') {
        type.value = 'Cryptocurrencies';
      } else if (jsondata.type == 'Forex') {
        type.value = 'Forex';
      } else if (jsondata.type == 'CARBON_TRADING') {
        type.value = 'Cryptocurrencies';
      }
    } else if (jsondata.name && !jsondata.type) {
      type.value = 'Futures';
    }
    if (type.value == 'Cryptocurrencies') {
      useRequest(getQueryCarbonTrading, { manual: true })
        .runAsync({})
        .then((data: any) => {
          let carbonTradingList = [] as { [key: string]: any }[];
          data.forEach((item: { [key: string]: any }) => {
            if (item.symbol == 'XAU') {
              carbonTradingList.unshift(item);
            } else {
              carbonTradingList.push(item);
            }
          });
          let datas = carbonTradingList as { [key: string]: any }[];
          useRequest(getQueryTokens, { manual: true })
            .runAsync({})
            .then((data: any) => {
              datas = [...datas, ...data] as { [key: string]: any }[];
              if (datas.length) {
                currencyList.value = datas.map((item) => {
                  item.name = item.symbol || item.pairsName;
                  item.lastPrice = item.price;
                  item.chgPct = item.updown > 0 ? '+' + item.updown + '%' : item.updown + '%';
                  item.chg = item.chPrice;
                  return item;
                });
                let chuanzhi: { [xx: string]: any } = {};

                if (jsondata.pairsName) {
                  chuanzhi = currencyList.value.filter((item) => {
                    return item.name == jsondata.pairsName || item.name == jsondata.symbol;
                  })[0];
                } else {
                  chuanzhi = currencyList.value[0];
                  if (isFrist.value) {
                    localStorage.setItem('trade', JSON.stringify(chuanzhi));
                  }
                }
                if (popupShow.value || !isFrist.value) return;
                isFrist.value = false;
                onClickItem(chuanzhi, true);
              }
            });
        });
    }
  }
  const times = () => {
    timer.value = setInterval(methodCurrencyList, 5000);
  };
  onActivated(() => {
    times();
    methodCurrencyList();
  });
  onDeactivated(() => {
    isFrist.value = true;
    clearInterval(timer.value);
    timer.value = null;
  });

  // 弹出框显示
  const [popupShow, onToggleShow] = useToggle(false);
  // 转换单位
  const handleUnit = (value: any) => {
    let newValue = '';
    if (!value) {
      newValue = '0';
    } else if (Number(value) >= 1000000000) {
      newValue = (Number(value) / 1000000000).toFixed(2) + 'B';
    } else if (Number(value) < 1000000) {
      newValue = (Number(value) / 1000).toFixed(2) + 'K';
    } else {
      newValue = (Number(value) / 1000000).toFixed(2) + 'M';
    }
    return newValue;
  };
</script>
<template>
  <div class="trade_popup">
    <div @click="() => !disabled && onToggleShow(true)">
      <slot></slot>
    </div>
    <VarPopup
      class="trade-popup"
      :show="popupShow"
      position="bottom"
      @close="onToggleShow(false)"
      @click-overlay="onToggleShow(false)"
    >
      <div style="max-height: 80vh">
        <div class="makets">
          <!-- <van-tabs v-model:active="type">
            <van-tab name="Cryptocurrencies" :title="$t('Cryptocurrencies')" />
            <van-tab name="Forex" :title="$t('Forex')" />
            <van-tab name="Futures" :title="$t('Futures')" />
          </van-tabs> -->
        </div>
        <!-- <div class="rank_box_th">
          <p class="width1">{{ $t('Currency') }}</p>
          <p class="width2">{{ $t('price') }} </p>
          <p class="width3">{{ $t('Change') }}</p>
        </div> -->
        <div class="rank_box_list">
          <div
            class="rank_box_li"
            @click="onClickItem(item, '1')"
            v-for="(item, index) in currencyList"
            :key="index"
          >
            <div class="width1 flex_center">
              <div class="img_box" v-if="!item.type">
                <div class="flag flag1">
                  <img :src="$img(`country/${item.name.split('/')[0]}.png`)" alt="" />
                </div>
                <div class="flag flag2">
                  <img :src="$img(`country/${item.name.split('/')[1]}.png`)" alt="" />
                </div>
              </div>
              <div class="img_box" v-else-if="item.type == 'CONTRACT'">
                <div class="flag1">
                  <img
                    :src="`https://s2.coinmarketcap.com/static/img/coins/64x64/${
                      imgsmap[item.name.split('/')[0]]
                    }.png`"
                    alt=""
                  />
                </div>
              </div>
              <div class="img_box" v-else-if="item.type == 'CARBON_TRADING'">
                <div class="flag1">
                  <img :src="`/${item.symbol}.png`" />
                </div>
              </div>
              <div class="rank_box_text">
                <div style="color: rgba(255, 255, 255, 0.85); font-size: 15px; font-weight: 700">
                  <span v-if="item.type === 'CONTRACT'">{{ item.pairsName }}</span>
                  <span v-else> {{ item.showPairsName || item.name }}/USD</span>
                </div>
                <div class="volume" v-if="item.volume">
                  {{ $t('volume1') }} {{ handleUnit(item.volume) }}</div
                >
              </div>
            </div>
            <div
              class="width2"
              :class="item.chg > 0 || item.updown > 0 ? 'font_green' : 'font_red'"
            >
              <div style="font-size: 16px; font-weight: normal">{{ item.lastPrice }}</div>
              <div style="font-size: 12px">{{ item.chgPct }}</div>
            </div>
            <!-- <div class="width3">
              <span class="width3_content">{{ $t('Trade') }}</span>
            </div> -->
          </div>
        </div>
      </div>
    </VarPopup>
  </div>
</template>
<style lang="scss">
  .font-color {
    color: #0063f5;
  }
  .trade_popup {
    .trade-popup {
      border-radius: 50px 50px 0px 0px;
      background: #242424;
      padding: 30px 0 20px;
      .flex_center {
        display: flex;
        height: 60px;
        align-items: center;
      }
      .rank_box_th {
        @include align-center;
        background: $body;
        height: 50px;
        font-size: 20px;
        padding: 0 30px;
        color: #666666;
        margin-top: 30px;
      }
      .rank_box_list {
        margin: 0 30px;
      }
      .rank_box_li {
        height: 120px;
        border-radius: 16px;
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.07);
        background: $body;
        @include align-center;
        justify-content: space-between;
        margin-bottom: 20px;
        padding: 30px 20px 30px 20px;
        .img_box {
          width: 80px;
          height: 80px;
          background: #242424;
          border-radius: 50%;
          margin-right: 10px;
          position: relative;
          .flag {
            width: 40px;
            height: 40px;
            position: absolute;
          }
          .flag1 {
            top: 12px;
            left: 10px;
            > img {
              border-radius: 50%;
            }
          }
          .flag2 {
            top: 30px;
            left: 30px;
          }
        }
        .rank_box_text {
          font-size: 26px;
          font-weight: 800;
          flex: 1;
          .volume {
            margin-top: 12px;
            color: rgba(255, 255, 255, 0.45);
            font-size: 24px;
            font-weight: normal;
          }
        }
        .flex_center {
          display: flex;
          align-items: center;
        }
      }
      .width1 {
        max-width: 70%;
      }
      .width2 {
        text-align: right;
      }
      .width3_content {
        @include center;
        width: 160px;
        height: 60px;
        border-radius: 30px;
        color: #0063f5;
        background-color: #e5effe;
      }

      .red_bg {
        background: $primary-red;
      }
      .green_bg {
        background: $primary-green;
      }
    }

    .makets {
      background: #f6f7fb;
      width: 95%;
      margin: 0 auto;
      .tabs {
        padding: 20px 30px 0 30px;
      }
    }
  }
</style>
<style lang="scss">
  .trade_popup {
    .makets {
      .van-tabs__nav {
        justify-content: space-between;
      }
      .van-tabs__nav--line {
        padding-bottom: 0;
      }
      .van-tab {
        background: rgb(229, 239, 254);
        min-width: 200px;
        height: 68px;
        border-radius: 34px;
        font-size: 27px;
        padding: 0 25px;
        flex: 0;
      }
      .van-tabs__line {
        display: none;
      }
      .van-tab--active {
        background: rgb(0, 99, 245);
        color: #fff;
      }
      .search_box {
        padding-bottom: 0;
        height: 56px;

        .var-input,
        .var-field-decorator,
        .var-field-decorator__controller {
          height: 56px;
          line-height: 56px;
          border-radius: 900px;
          font-size: 28px;
        }

        .var-input__input {
          height: 36px;
        }

        .icon-sousuo {
          font-size: 28px;
          color: #7a7a7a;
        }

        .var-field-decorator__controller {
          padding-left: 30px;
        }
      }
    }
  }
</style>
